package servlet;

import database.DataBaseConnection;
import org.apache.log4j.PropertyConfigurator;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Properties;

@WebServlet(name = "Log4jInitServlet")
public class Log4jInitServlet extends HttpServlet {
    public void init(ServletConfig config) throws ServletException {
        //初始化log4j配置文件
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("log4j.properties");
        PropertyConfigurator.configure(inputStream);

        //初始化数据库连接字符串
        Properties properties = new Properties();
        InputStream input = classLoader.getResourceAsStream("connection.properties");
        try {
            properties.load(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String host = properties.getProperty("host");
        String port = properties.getProperty("port");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        String database = properties.getProperty("database");
        String connectionUrl = "jdbc:mysql://" + host + ":" + port + "/" + database
                + "?useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&user=" + username + "&password="
                + password + "&useUnicode=true&allowMultiQueries=true&characterEncoding=UTF8&useSSL=false";
        DataBaseConnection.setConnnectionURL(connectionUrl);

        try {
            inputStream.close();
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.init(config);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    }
}
